package com.googlecode.bizyap.impl.tomcat.realm;

import java.security.Principal;

import org.apache.catalina.Realm;
import org.apache.catalina.realm.JAASRealm;

import com.googlecode.bizyap.core.Application;
import com.googlecode.bizyap.core.SSOContext;
import com.googlecode.bizyap.core.logging.Logger;
import com.googlecode.bizyap.core.logging.LoggerFactory;

public class TomcatSSORealm extends JAASRealm implements Realm {
	
	private static final Logger log = LoggerFactory.getLogger(TomcatSSORealm.class);
	
	@Override
	public Principal authenticate(String username, String credentials){
		Application app = SSOContext.getApplication();
		if(log.isDebugEnabled())log.debug(app);

		if(app==null || !app.isSSOApplication()){
			return super.authenticate(username, credentials);
		}
		else {
			return getPrincipal(username);
		}
	}

	@Override
	protected String getName() {
		return getClass().getSimpleName();
	}

	@Override
	protected Principal getPrincipal(String username) {
		Application app = SSOContext.getApplication();
		if(log.isDebugEnabled())log.debug(app);

		if(app==null || !app.isSSOApplication()){
			return super.getPrincipal(username);
		}
		else {
			return SSORealmHelper.getPrincipal(username);
		}
	}
	
	@Override
	public boolean hasRole(Principal principal, String role) {
		Application app = SSOContext.getApplication();
		if(log.isDebugEnabled())log.debug(app);

		if(app==null || !app.isSSOApplication()){
			return super.hasRole(principal, role);
		}
		else {
			return SSORealmHelper.hasRole(principal, role);
		}
    }
}
